package edu.bw.dao.impl;

import edu.bw.dao.ProductDao;
import edu.bw.po.Product;
import edu.bw.utils.ConnectionFactory;
import jakarta.annotation.Resource;
import lombok.Setter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;
@Setter
@Repository
public class ProductDaoImpl implements ProductDao {
    //交给spring注入
    @Resource
    private QueryRunner queryRunner;

    //用setter注入
    public void setQueryRunner(QueryRunner queryRunner){
        this.queryRunner=queryRunner;
    }

    @Autowired
    private ConnectionFactory connectionFactory;


    @Override
    public void updateProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConn(),"UPDATE spring.product SET pname=?,price=?,category=? WHERE pid=?" ,
                    product.getPname(),product.getPrice(),product.getCategory(),product.getPid());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Product> findAll() {
        try {
            return queryRunner.query(connectionFactory.currentThreadConn(),"SELECT * FROM spring.product",new BeanListHandler<>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
